﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Reflection;
using System.IO;

namespace GSLMS.Core
{
    public class ServiceFactory
    {
        private static IUnityContainer container = new UnityContainer();
        private static string filePath = string.Empty;

        static ServiceFactory()
        {
            filePath = AppDomain.CurrentDomain.BaseDirectory;
            Register(LoadService());
        }

        public static T GetService<T>() where T : class
        {
            return container.Resolve<T>(new ResolverOverride[0]);
        }

        public static T GetService<T>(string name) where T : class
        {
            return container.Resolve<T>(name, new ResolverOverride[0]);
        }

        public static T LazyT<T>() where T : class
        {
            Lazy<T> lazy = new Lazy<T>(delegate
            {
                return GetService<T>();
            });
            return lazy.Value;
        }
        public static T LazyT<T>(string name) where T : class
        {
            Lazy<T> lazy = new Lazy<T>(delegate
            {
                return GetService<T>(name);
            });
            return lazy.Value;
        }
        private static Assembly LoadService()
        {
            return Assembly.LoadFile(Directory.GetFiles(filePath + @"\bin", "*.Services.dll").FirstOrDefault<string>());
        }

        private static void Register(Assembly service)
        {
            foreach (Type type in service.GetTypes())
            {
                Type[] interfaces = type.GetInterfaces();
                bool flag = interfaces.Length > 1;
                foreach (Type type2 in interfaces)
                {
                    if (flag)
                    {
                        container.RegisterType(type2, type, type2.Name, new InjectionMember[0]);
                    }
                    else
                    {
                        container.RegisterType(type2, type, new InjectionMember[0]);
                    }
                }
            }
        }

    }
}
